const { asyncHandler } = require('../middleware/errorHandler');
const { success, error } = require('../utils/common');
const Notification = require('../models/Notification');
const logger = require('../utils/logger');

class NotificationController {
  /**
   * 获取通知列表
   */
  static getNotifications = asyncHandler(async (req, res) => {
    const { page = 1, limit = 20, type, is_read } = req.query;

    const where = { user_id: req.user.id };
    if (type) where.type = type;
    if (is_read !== undefined) where.is_read = is_read === 'true';

    const offset = (page - 1) * limit;

    const { count, rows } = await Notification.findAndCountAll({
      where,
      offset,
      limit: parseInt(limit),
      order: [['created_at', 'DESC']]
    });

    res.json({
      code: 200,
      message: '获取成功',
      data: {
        list: rows,
        total: count,
        page: parseInt(page),
        limit: parseInt(limit),
        total_pages: Math.ceil(count / limit)
      }
    });
  });

  /**
   * 获取未读通知数量
   */
  static getUnreadCount = asyncHandler(async (req, res) => {
    const count = await Notification.count({
      where: {
        user_id: req.user.id,
        is_read: false
      }
    });

    res.json(success({ count }, '获取成功'));
  });

  /**
   * 标记通知为已读
   */
  static markAsRead = asyncHandler(async (req, res) => {
    const { id } = req.params;

    if (id === 'all') {
      // 标记所有通知为已读
      await Notification.update(
        { is_read: true, read_time: new Date() },
        {
          where: {
            user_id: req.user.id,
            is_read: false
          }
        }
      );

      logger.info(`用户 ${req.user.id} 标记所有通知为已读`);
    } else {
      // 标记单个通知为已读
      const notification = await Notification.findOne({
        where: { id, user_id: req.user.id }
      });

      if (!notification) {
        return res.status(404).json(error('通知不存在'));
      }

      await notification.update({
        is_read: true,
        read_time: new Date()
      });

      logger.info(`用户 ${req.user.id} 标记通知为已读: ${id}`);
    }

    res.json(success(null, '标记成功'));
  });

  /**
   * 删除通知
   */
  static deleteNotification = asyncHandler(async (req, res) => {
    const { id } = req.params;

    const notification = await Notification.findOne({
      where: { id, user_id: req.user.id }
    });

    if (!notification) {
      return res.status(404).json(error('通知不存在'));
    }

    await notification.destroy();

    logger.info(`用户 ${req.user.id} 删除通知: ${id}`);

    res.json(success(null, '删除成功'));
  });

  /**
   * 批量删除通知
   */
  static batchDeleteNotifications = asyncHandler(async (req, res) => {
    const { ids } = req.body;

    if (!ids || !Array.isArray(ids)) {
      return res.status(400).json(error('请选择要删除的通知'));
    }

    await Notification.destroy({
      where: {
        id: ids,
        user_id: req.user.id
      }
    });

    logger.info(`用户 ${req.user.id} 批量删除通知: ${ids.join(',')}`);

    res.json(success(null, '删除成功'));
  });

  /**
   * 创建系统通知
   */
  static createSystemNotification = asyncHandler(async (req, res) => {
    const { user_ids, title, content, type = 'system' } = req.body;

    if (!user_ids || !title || !content) {
      return res.status(400).json(error('参数不完整'));
    }

    const notifications = [];
    const userIds = Array.isArray(user_ids) ? user_ids : [user_ids];

    for (const userId of userIds) {
      notifications.push({
        user_id: userId,
        title,
        content,
        type
      });
    }

    await Notification.bulkCreate(notifications);

    logger.info(`管理员创建系统通知: ${title}`);

    res.json(success(null, '通知发送成功'));
  });

  /**
   * 创建课程相关通知
   */
  static createCourseNotification = asyncHandler(async (req, res) => {
    const { course_id, user_ids, title, content } = req.body;

    if (!course_id || !user_ids || !title || !content) {
      return res.status(400).json(error('参数不完整'));
    }

    const notifications = [];
    const userIds = Array.isArray(user_ids) ? user_ids : [user_ids];

    for (const userId of userIds) {
      notifications.push({
        user_id: userId,
        title,
        content,
        type: 'course',
        related_id: course_id
      });
    }

    await Notification.bulkCreate(notifications);

    logger.info(`创建课程通知: ${title}, 课程ID: ${course_id}`);

    res.json(success(null, '通知发送成功'));
  });

  /**
   * 创建支付相关通知
   */
  static createPaymentNotification = asyncHandler(async (req, res) => {
    const { user_id, title, content, order_id } = req.body;

    if (!user_id || !title || !content) {
      return res.status(400).json(error('参数不完整'));
    }

    await Notification.create({
      user_id,
      title,
      content,
      type: 'payment',
      related_id: order_id
    });

    logger.info(`创建支付通知: ${title}, 用户ID: ${user_id}`);

    res.json(success(null, '通知发送成功'));
  });

  /**
   * 创建直播相关通知
   */
  static createLiveNotification = asyncHandler(async (req, res) => {
    const { user_ids, title, content, live_id } = req.body;

    if (!user_ids || !title || !content) {
      return res.status(400).json(error('参数不完整'));
    }

    const notifications = [];
    const userIds = Array.isArray(user_ids) ? user_ids : [user_ids];

    for (const userId of userIds) {
      notifications.push({
        user_id: userId,
        title,
        content,
        type: 'live',
        related_id: live_id
      });
    }

    await Notification.bulkCreate(notifications);

    logger.info(`创建直播通知: ${title}, 直播ID: ${live_id}`);

    res.json(success(null, '通知发送成功'));
  });
}

module.exports = NotificationController; 